﻿using Microsoft.SharePoint;
using System;
using System.Collections.Generic;

namespace SP.FeatureAdministrationTool.FeatureManagerModule
{
    public class SiteFeatureManager : FeatureManager
    {
        private Guid siteCollectionId;
        private Guid siteId;

        public SiteFeatureManager(Guid siteCollectionId, Guid siteId)
        {
            this.siteCollectionId = siteCollectionId;
            this.siteId = siteId;
        }

        public override void ActivateFeature(Guid featureId)
        {
            using (SPSite site = new SPSite(siteCollectionId)) // too many new instance
            {
                using (SPWeb web = site.OpenWeb(this.siteId))
                {
                    web.Features.Add(featureId);
                }
            }
        }

        public override void DeactivateFeature(Guid featureId)
        {
            using (SPSite site = new SPSite(siteCollectionId))
            {
                using (SPWeb web = site.OpenWeb(this.siteId))
                {
                    web.Features.Remove(featureId);
                }
            }
        }

        public override List<Feature> GetAllFeatures()
        {
            List<Feature> features = new List<Feature>();
            using (SPSite site = new SPSite(this.siteCollectionId))
            {
                using (SPWeb web = site.OpenWeb(this.siteId))
                {
                    foreach (Feature feature in this.GetFeatures(SPFeatureScope.Web))
                    {
                        try
                        {
                            feature.Status = web.Features[feature.Id] == null ? FeatureActivationStatus.Deactivated : FeatureActivationStatus.Activated;
                            features.Add(feature);
                        }
                        catch
                        {
                        }
                    }
                }
            }

            return features;
        }
    }
}
